import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

np.random.seed(0)
X = np.sort(5 * np.random.rand(80, 1), axis=0)
y = np.cos(X).ravel() + np.random.randn(80) * 0.1

# 使用多项式特征拓展
ploy = PolynomialFeatures(degree=4)
X_poly = ploy.fit_transform(X)

# 创建线性回归模型
model = LinearRegression()
model.fit(X_poly, y)

# 预测
X_test = np.linspace(0, 5, 100)[:, np.newaxis]
X_test_poly = ploy.transform(X_test)
y_pred = model.predict(X_test_poly)

# 绘制原始数据和拟合曲线
plt.scatter(X, y, label='Original Data')
plt.plot(X_test, y_pred, label='Polynomial Regression', color='r')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.title('Polynomial Regression Example')
plt.show()
